package com.module.overview.ui.schedule.provider

import android.graphics.Typeface
import android.view.View
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.core.RouterHub
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.home.ScoringFactorsModel
import com.common.app.data.bean.overView.CardSettingModel
import com.common.app.data.repository.HomeApi
import com.common.app.helper.RouterHelper
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.setSafeOnClickListener
import com.common.base.app.extras.setVisible
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.common.app.widget.AnimatedRoundProgressBar
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.yes
import com.common.base.data.CommonBean
import com.common.base.utils.JsonUtils
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getString
import com.module.ble.data.bean.CusChartData
import com.module.ble.repo.BloodOxygenRepo
import com.module.ble.repo.HeartRateRepo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import rxhttp.toFlow
import rxhttp.wrapper.param.RxHttp
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/6/16
 *
 * 描述：体征卡片
 *
 * 修订历史：完成度100%
 *
 */
class OvMainSignsCardProvider(
    override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_SIGNS,
    override val layoutId: Int = R.layout.overview_main_signs_crad_provider
) : BaseItemProvider<CardSettingModel>() {

    var tvHeartRate: TextView? = null
    var tvBloodOxygen: TextView? = null
    var tvOverallScoring: TextView? = null
    var rpdSigns: AnimatedRoundProgressBar? = null

    private var requestJob: Job? = null
    var scope = CoroutineScope(Dispatchers.IO)

    init {
    }

    override fun convert(helper: BaseViewHolder, item: CardSettingModel) {
        helper.getView<View>(R.id.totalSignsCard).setSafeOnClickListener {
            RouterHelper.navigationPostcard(RouterHub.ROUTER_OVERVIEW_CARD_HISTORY_DETAILS)
                .withString(KeyBundle.BUNDLE_TITLE, item.name)
                .navigation()
        }
        helper.itemView.setVisible(item.isEnabled)

        getTheDayHr()
        getTheDayOxy()
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        tvHeartRate = viewHolder.getView(R.id.tvHeartRate)
        tvBloodOxygen = viewHolder.getView(R.id.tvBloodOxygen)
        tvOverallScoring = viewHolder.getView(R.id.tvOverallScoring)
        rpdSigns = viewHolder.getView(R.id.rpdSigns)
        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun onViewDetachedFromWindow(holder: BaseViewHolder) {
        super.onViewDetachedFromWindow(holder)
    }


    /**
     * 获取当天心率
     */
    fun getTheDayHr(){

        doOnIOThread {
            //当天心率
            HeartRateRepo.instance.findLatestByDay(TimeUtils.getTimeDateLong())?.let { originalIt->
                doOnUiThread {
                    tvHeartRate?.text = "${originalIt.heartRate}${getString(R.string.common_times_per_minute_splice)}"
                }
            }
        }
    }

    /**
     * 获取当天血氧
     */
    fun getTheDayOxy(){
        doOnIOThread {
            //当天血氧
            BloodOxygenRepo.instance.findLatestByDay(TimeUtils.getTimeDateLong())?.let { originalIt->
                doOnUiThread {
                    tvBloodOxygen?.text = "${originalIt.bloodOxygen}${getString(R.string.common_bfb_unit)}"
                }
            }
        }
    }


    // 手动取消请求
    fun cancelRequest() {
        requestJob?.cancel()
        requestJob = null
    }

    private fun getSleepScoringFactors() {
        // 取消之前的请求
        requestJob?.cancel()

        requestJob = scope.launch {
            RxHttp.postJson(HomeApi.GET_SIGNS_SCORING_FACTORS)
                .add("date", TimeUtils.getYearMonthDay(TimeUtils.getTimeDateLong()))
                .toFlow<CommonBean<ScoringFactorsModel>>()
                .catch { e ->
                    // 处理异常
                }.collect { responseIt->
                    responseIt.isSuccess().yes {
                        responseIt.Data?.let { dataIt->
                            doOnUiThread {
                                tvOverallScoring?.text = dataIt.total_score.toInt().toString()
                            }
                        }
                    }
                }
        }
    }
}